<script setup>
import IMG_01 from './assets/1.jpg'
import IMG_02 from './assets/2.jpg'
import IMG_03 from './assets/3.jpg'
import IMG_04 from './assets/4.jpg'
import IMG_05 from './assets/5.jpg'
import IMG_06 from './assets/6.jpg'
import IMG_07 from './assets/7.jpg'
import IMG_08 from './assets/8.jpg'
import IMG_09 from './assets/9.jpg'
import IMG_10 from './assets/10.jpg'
import IMG_11 from './assets/11.jpg'
import IMG_12 from './assets/12.jpg'
import IMG_13 from './assets/13.jpg'
import {onMounted, onUnmounted} from "vue";

const lazyImg = () => {
  // 获取可视区高度
  const viewHeight = document.body.offsetHeight
  // 获取带有data-src属性的所有img标签
  let imgList = document.querySelectorAll('img[data-src]')
  // 遍历所有的img，获取img距离适口上下左右的位置
  imgList.forEach(item => {
    // 用dataset获取自定义属性
    if (item.dataset.src === '') return
    // 用于获得页面中某个元素的左，上，右和下分别相对浏览器视窗的位置
    let rect = item.getBoundingClientRect()
    // 判断当前图片是否超过
    if (rect.bottom >= 0 && rect.top < viewHeight) {
      item.src = item.dataset.src
      item.removeAttribute('data-src')
    }
  })
}

onMounted(() => {
  window.addEventListener('scroll', lazyImg)
})

onUnmounted(() => {
  window.removeEventListener('scroll', lazyImg)
})
</script>

<template>
  <div class="img-list">
    <!--  注意：需要在src中存一个默认的图片  -->
    <img :data-src="IMG_01" :src="IMG_01" alt="">
    <img :data-src="IMG_02" :src="IMG_01" alt="">
    <img :data-src="IMG_03" :src="IMG_01" alt="">
    <img :data-src="IMG_04" :src="IMG_01" alt="">
    <img :data-src="IMG_05" :src="IMG_01" alt="">
    <img :data-src="IMG_06" :src="IMG_01" alt="">
    <img :data-src="IMG_07" :src="IMG_01" alt="">
    <img :data-src="IMG_08" :src="IMG_01" alt="">
    <img :data-src="IMG_09" :src="IMG_01" alt="">
    <img :data-src="IMG_10" :src="IMG_01" alt="">
    <img :data-src="IMG_11" :src="IMG_01" alt="">
    <img :data-src="IMG_12" :src="IMG_01" alt="">
    <img :data-src="IMG_13" :src="IMG_01" alt="">
  </div>
</template>

<style>
body, html, #app {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
.img-list img {
  width: 100%;
  height: 100%;
}
</style>
